package core.transfer;

import java.io.File;
import java.io.IOException;

import java.net.*;
import java.io.*;

/**
 * Class HTTPTranfer : Enables to copy a file from a remote server or to a remote server using http protocol
 * @project Universalcopy
 * @author Aurele TONNERRE, Romain Monnier
 */
public class HTTPTransfer extends ProtocolTransfer
{
    
    
    /**
     * Constructs HTTPTranfer with the file path and the directory path
     * @param fullUrlSource : the fullpath of the file to copy
     * @param fullUrlCible : the fullpath of the directory
     * @param theFile : informations about the file
     */
    public HTTPTransfer(String fullUrlSource, String fullUrlCible, core.File theFile) {
        
        super(fullUrlSource, fullUrlCible);
        file = theFile.getFile();
        
        
    }

    @Override
    public void download() {
        
        urlDestination = completeUrl(urlDestination);
        
        File destFile = new File(urlDestination.toString()+file.getName());
        
        
        try
        {
           /*
            * Get a connection to the URL and start up
            * a buffered reader.
            */
           long startTime = System.currentTimeMillis();

           URL url = new URL(urlOrigin);
           url.openConnection();
           InputStream reader = url.openStream();

           /*
            * Setup a buffered file writer to write
            * out what we read from the website.
            */
           FileOutputStream writer = new FileOutputStream(urlDestination.toString()+file.getName());
           byte[] buffer = new byte[153600];
           int totalBytesRead = 0;
           int bytesRead = 0;


           while ((bytesRead = reader.read(buffer)) > 0)
           {  
              writer.write(buffer, 0, bytesRead);
              buffer = new byte[153600];
              totalBytesRead += bytesRead;
           }

           long endTime = System.currentTimeMillis();

           writer.close();
           reader.close();
        }
        catch (MalformedURLException e)
        {
           e.printStackTrace();
        }
        catch (IOException e)
        {
           e.printStackTrace();
        }
        

    }

    @Override
    public void upload(File sourceFile, String destURL) throws IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void upload() throws IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    
    
    
}
